package org.nf.trading.service.app.circle.mq.confirm;

import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.RequiredArgsConstructor;
import org.nf.trading.dto.LikeDTO;
import org.nf.trading.service.app.circle.enums.RedisKeyEnum;
import org.nf.trading.service.app.circle.mq.ConfirmCallbackService;
import org.springframework.amqp.core.Message;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.io.IOException;

/**
 * @author wangl
 * @date 2023/12/11
 */
@Service
@RequiredArgsConstructor
public class LikeConfirmCallbackService implements ConfirmCallbackService {

    private final RedisTemplate<String, Integer> redisTemplate;

    @Override
    public void confirmCallback(Message message) {
        byte[] bytes = message.getBody();
        try {
            LikeDTO vo = new ObjectMapper().readValue(bytes, LikeDTO.class);
            //如果是取消点赞，则将redis取消的userId和postId添加回去
            if(vo.getLikeStatus()) {
                redisTemplate.opsForSet()
                        .add(RedisKeyEnum.POST_LIKE_PREFIX.getValue() + vo.getPostId(), vo.getUserId());
            } else {
                //否则删除redis中的userId和postId
                redisTemplate.opsForSet()
                        .remove(RedisKeyEnum.POST_LIKE_PREFIX.getValue() + vo.getPostId(), vo.getUserId());
            }
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }
}